<!--
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2023-09-12 09:38:27
 * @LastEditors: 甯左龙 1173405584@qq.com
 * @Description:
 * @FilePath: \wms-v2\src\ve\elements\form\uiDate\uiDate.vue
 * CIMC-V2
-->
<template>
  <UiFormItem :class="{ hidden: conditionProperty.hidden || info.extension.hidden.value }" :info="info">
    <div class="w-full" @keyup.enter="$handleEnter">
      <el-date-picker
        :ref="info._id"
        v-model="formDataModel"
        clearable
        :disabled="conditionProperty.disabled || info.extension.disabled.value"
        :disabled-date="
          info.extension?.nowDateLimit?.value
            ? disabledDate
            : () => {
                return false
              }
        "
        :placeholder="info.extension.placeholder.value"
        popper-class="wms-picker-panel"
        :shortcuts="shortcutsList"
        :size="info.extension.size.value"
        :type="modelSelection"
        :value-format="valueFormat"
        :default-time="defaultTime"
        @change="handleChange"
      />
    </div>
  </UiFormItem>
</template>
<script>
  import { defineComponent } from 'vue'
  import { UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin } from '@ve/mixin'
  import { getDefaultDate } from '@ve/utils/utils'
  export default defineComponent({
    name: 'UiDate',
    components: {},
    mixins: [UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin],
    emits: ['keyup'],
    data() {
      return {
        modelData: {},
        shortcuts: {
          dateShortcuts: [
            {
              text: '当前',
              value: () => {
                return new Date()
              },
            },
            {
              text: '昨天',
              value: () => {
                const start = new Date()
                return start.getTime() - 3600 * 1000 * 24
              },
            },
            {
              text: '前天',
              value: () => {
                const start = new Date()
                return start.getTime() - 3600 * 1000 * 24 * 2
              },
            },
            {
              text: '一周前',
              value: () => {
                const start = new Date()
                return start.getTime() - 3600 * 1000 * 24 * 7
              },
            },
            {
              text: '一月前',
              value: () => {
                const start = new Date()
                return start.getTime() - 3600 * 1000 * 24 * 30
              },
            },
            {
              text: '半年前',
              value: () => {
                const start = new Date()
                return start.getTime() - 3600 * 1000 * 24 * 182
              },
            },
            {
              text: '一年前',
              value: () => {
                const start = new Date()
                return start.getTime() - 3600 * 1000 * 24 * 365
              },
            },
          ],
          dateRangeShortcuts: [
            {
              text: '近一周',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                return [start, end]
              },
            },
            {
              text: '近一月',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                return [start, end]
              },
            },
            {
              text: '近半年',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 182)
                return [start, end]
              },
            },
            {
              text: '近一年',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
                return [start, end]
              },
            },
          ],
          DECDateRangeShortcuts: [
            {
              text: '今天',
              value: () => {
                const end = new Date()
                const start = new Date()
                const today = getDefaultDate('now')
                start.setTime(new Date(`${today.split(' ')[0]} 00:00:00`).getTime())
                end.setTime(new Date(`${today.split(' ')[0]} 23:59:59`).getTime())
                return [start, end]
              },
            },
            {
              text: '近三天',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
                return [start, end]
              },
            },
            {
              text: '近三月',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                return [start, end]
              },
            },
          ],
        },
        shortcutsList: [],
        valueFormat: '',
        disabledDate: () => {
          return false
        },
      }
    },
    computed: {
      modelSelection() {
        return this.info.extension.selection.value
      },
      defaultTime() {
        const timeList = this.info.extension.defaultTime ? this.info.extension.defaultTime.value : ['00:00:00', '00:00:00']
        return this.info.extension.selection.value === 'datetimerange'
          ? [new Date(`2000-01-01 ${timeList[0]}`), new Date(`2000-01-01 ${timeList[1]}`)]
          : new Date('2000-01-01 00:00:00')
      },
    },
    watch: {
      modelSelection() {
        this.formDataModel = ''
      },
      formDataModel(newVal, oldVal) {
        if (!newVal && Array.isArray(oldVal)) {
          // 如果为时间范围的清空 则需要将提取出来的值一并清空
          const formSelf = this.vuiComponents[this.formId] && this.vuiComponents[this.formId].self
          const fromData = formSelf && formSelf.info.data.formData
          if (fromData) {
            const startSuffix = this.info.extension?.startSuffix?.value ? this.info.extension?.startSuffix?.value : '_start'
            const endSuffix = this.info.extension?.endSuffix?.value ? this.info.extension?.endSuffix?.value : '_end'
            fromData[`${this.info.extension.model.value}${startSuffix}`] = ''
            fromData[`${this.info.extension.model.value}${endSuffix}`] = ''
          }
        }
      },
    },
    created() {
      // 设置默认值
      this.setDefaultValue()
      // 设置时间限定函数
      if (this.info.extension?.nowDateLimit?.value) {
        const dateLimit = this.info.extension.nowDateLimit.value
        if (dateLimit === 'befor') {
          // 设置只能选择当前时之前
          this.disabledDate = this.disabledDateByBefor
        } else if (dateLimit === 'after') {
          // 设置只能选择当前时之后
          this.disabledDate = this.disabledDateByAfter
          // 重置快捷选择栏
          this.shortcuts = { dateShortcuts: [], dateRangeShortcuts: [] }
        }
      }
      // 生成快捷选项
      if (this.modelSelection.indexOf('month') === -1) {
        if (['datetime', 'date'].indexOf(this.modelSelection) !== -1) {
          this.shortcutsList = this.shortcuts.dateShortcuts
        } else {
          this.shortcutsList = [...this.shortcuts.DECDateRangeShortcuts, ...this.shortcuts.dateRangeShortcuts]
        }
      }
      // 生成值格式
      if (this.modelSelection.indexOf('month') > -1) {
        this.valueFormat = 'YYYY-MM'
      } else {
        this.valueFormat = this.modelSelection.indexOf('time') !== -1 ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD'
      }
    },
    mounted() {
      // 设置vuiComponents
      // console.log('this.$refs', this, this.$refs)
      this.vSetRef && this.vSetRef()
    },
    methods: {
      handleChange() {
        // console.log('this ------- date', this)
        // 触发条件判断值改变
        this.setPageModulesState('value', this.formDataModel)
        // 调用 change 事件
        this.onChange()
      },
      setDefaultValue() {
        if (this.info.extension.defaultDate && this.info.extension.defaultDate.value) {
          // 如果设置默认值为 当前
          if (this.info.extension.selection.value === 'datetime' || this.info.extension.selection.value === 'date') {
            // 如果当前组件类型为 datetime 或 date
            let dateType = this.info.extension.defaultDate.value
            if (['now', 'yesterday'].includes(dateType)) {
              // 设置 默认值为 当前 的默认值
              let defaultDate = getDefaultDate(dateType)
              // 如果为日期类型则去掉值的时分秒
              if (this.info.extension.selection.value.indexOf('time') == -1) {
                defaultDate = defaultDate.split(' ')[0]
              }
              this.formDataModel = defaultDate
            }
          } else if (this.info.extension.selection.value === 'datetimerange' || this.info.extension.selection.value === 'daterange') {
            // 如果当前组件类型为 时间范围
            if (this.info.extension.defaultDate.value !== 'now') {
              let defaultDate = getDefaultDate(this.info.extension.defaultDate.value)
              // 如果为日期类型则去掉值的时分秒
              if (this.info.extension.selection.value.indexOf('time') == -1) {
                defaultDate[0] = defaultDate[0].split(' ')[0]
                defaultDate[1] = defaultDate[1].split(' ')[0]
              }
              this.formDataModel = defaultDate
            }
          }
        }
      },
      disabledDateByBefor(dateObj) {
        const nowDate = Date.now()
        const dateObjUnix = dateObj.getTime()
        return nowDate < dateObjUnix
      },
      disabledDateByAfter(dateObj) {
        const nowDate = Date.now()
        const dateObjUnix = dateObj.getTime()
        return nowDate - 86400000 > dateObjUnix
      },
    },
  })
</script>
<style lang="scss" scoped>
  :deep() .el-input--prefix .el-input__inner {
    padding-left: 30px;
  }
</style>
